using Cysharp.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.EventSystems.EventTrigger;


[DisallowMultipleComponent]
/// <summary>
/// Buff组件
/// </summary>
public class BuffComponent : MonoBehaviour
{
    /// <summary>
    /// Buff字典
    /// </summary>
    private Dictionary<BuffType, BuffBase> m_Buffs;

    private void Start()
    {
        m_Buffs = new Dictionary<BuffType, BuffBase>();
    }

    /// <summary>
    /// 添加 Buff
    /// </summary>
    /// <param name="buffData">buff数据</param>
    /// <param name="caster">施法者</param>
    /// <param name="target">作用目标</param>
    public void AddBuff(BuffData buffData,Entity caster,Entity target)
    {
        Logger.Log("BuffComponent", $"AddBuff(BuffData) 被调用，target={target?.name}, buffName={buffData?.BuffName}, buffType={buffData?.BuffType}");
        
        if (buffData == null)
        {
            Logger.LogError("BuffComponent", $"BuffData 为空！target={target?.name}");
            return;
        }
        
        if (caster == null)
        {
            Logger.LogWarning("BuffComponent", $"Caster 为空，target={target?.name}, buffName={buffData.BuffName}");
        }
        
        if (target == null)
        {
            Logger.LogError("BuffComponent", $"Target 为空！buffName={buffData.BuffName}");
            return;
        }
        
        // 使用工厂模式创建Buff
        Logger.Log("BuffComponent", $"准备创建Buff，buffType={buffData.BuffType}, target={target.name}");
        BuffBase buffBase = BuffFactory.CreateBuff(buffData, caster, target);
        
        if (buffBase != null)
        {
            Logger.Log("BuffComponent", $"Buff创建成功，buffType={buffData.BuffType}, target={target.name}");
            AddBuff(buffBase);
        }
        else
        {
            Logger.LogError("BuffComponent", $"无法创建Buff: {buffData.BuffType}, target={target.name}");
        }
    }

    /// <summary>
    /// 添加 Buff
    /// </summary>
    /// <param name="newBuff"></param>
    public void AddBuff(BuffBase newBuff)
    {
        if (newBuff == null || newBuff.BuffData == null)
        {
            Logger.LogError("BuffComponent", $"newBuff 或 BuffData 为空！target={name}");
            return;
        }
        
        Logger.Log("BuffComponent", $"AddBuff(BuffBase) 被调用，target={name}, buffName={newBuff.BuffData.BuffName}, buffType={newBuff.BuffData.BuffType}");
        
        bool canReceive = CanReceive(newBuff.BuffData.Tags);
        Logger.Log("BuffComponent", $"CanReceive检查: {canReceive}, target={name}, buffName={newBuff.BuffData.BuffName}, tags={newBuff.BuffData.Tags}, immuneMask={ImmuneMask}");
        
        if (!canReceive)
        {
            Logger.LogWarning("BuffComponent", $"{name} 添加失败 {newBuff.BuffData.BuffName}，原因：被免疫 (tags={newBuff.BuffData.Tags}, immuneMask={ImmuneMask})");
            return;
        }

        //添加标签
        AddImmunity(newBuff.BuffData.Tags);
        Logger.Log("BuffComponent", $"添加免疫标签: {newBuff.BuffData.Tags}, 当前immuneMask={ImmuneMask}");

        if (m_Buffs.TryGetValue(newBuff.BuffData.BuffType,out var existing))
        {
            Logger.Log("BuffComponent", $"已存在相同类型的Buff: {newBuff.BuffData.BuffType}, 尝试添加层数或刷新");
            //buff 添加层数
            if (!existing.AddStack())
            {
                Logger.Log("BuffComponent", $"无法添加层数，刷新持续时间: {newBuff.BuffData.Duration}秒");
                existing.Refresh(newBuff.BuffData.Duration);
            }
            else
            {
                Logger.Log("BuffComponent", $"成功添加层数");
            }
            newBuff.Dispose();
            return;
        }

        Logger.Log("BuffComponent", $"添加新Buff到字典: {newBuff.BuffData.BuffType}, target={name}");
        m_Buffs.Add(newBuff.BuffData.BuffType, newBuff);
        Logger.Log("BuffComponent", $"启动Buff异步执行: {newBuff.BuffData.BuffName}, target={name}");
        RunBuffAsync(newBuff).Forget();
    }

    private async UniTask RunBuffAsync(BuffBase buff)
    {
        Logger.Log("BuffComponent", $"RunBuffAsync 开始，buffName={buff.BuffData.BuffName}, target={name}");
        await buff.RunAsync();
        Logger.Log("BuffComponent", $"RunBuffAsync 完成，移除Buff: {buff.BuffData.BuffName}, target={name}");
        m_Buffs.Remove(buff.BuffData.BuffType);
        RemoveImmunity(buff.BuffData.Tags);
        Logger.Log("BuffComponent", $"Buff已从字典移除，buffType={buff.BuffData.BuffType}, target={name}");
    }

    public void RemoveBuff(BuffType type)
    {
        if (m_Buffs.TryGetValue(type, out var buff))
        {
            buff.Cancel();
            RemoveImmunity(buff.BuffData.Tags);
        }
    }

    /// <summary>
    /// Buff Tag 
    /// </summary>
    public BuffTag ImmuneMask { get; private set; }

    /// <summary>
    /// 检查某 Buff 是否能被添加
    /// </summary>
    /// <param name="tags">Buff 配置，内含 tags 字段</param>
    public bool CanReceive(BuffTag tags)
    {
        // 如果 Buff 的任意标签在免疫掩码中，则免疫
        return (ImmuneMask & tags) == 0;
    }

    /// <summary> 
    /// 动态添加免疫标签
    /// </summary>
    public void AddImmunity(BuffTag tag) => ImmuneMask |= tag;

    /// <summary> 
    /// 动态移除免疫标签
    /// </summary>
    public void RemoveImmunity(BuffTag tag) => ImmuneMask &= ~tag;

    /// <summary> 
    /// 一次性设置完整掩码
    /// </summary>
    public void SetImmunityMask(BuffTag mask) => ImmuneMask = mask;

    /// <summary>
    /// 获取所有活跃的Buff
    /// </summary>
    /// <returns>活跃的Buff列表</returns>
    public List<BuffBase> GetActiveBuffs()
    {
        var activeBuffs = new List<BuffBase>();
        foreach (var buff in m_Buffs.Values)
        {
            if (buff != null && !buff.IsFinished())
            {
                activeBuffs.Add(buff);
            }
        }
        return activeBuffs;
    }

    /// <summary>
    /// 获取指定类型的Buff
    /// </summary>
    /// <param name="buffType">Buff类型</param>
    /// <returns>指定类型的Buff，如果不存在则返回null</returns>
    public BuffBase GetBuff(BuffType buffType)
    {
        m_Buffs.TryGetValue(buffType, out var buff);
        return buff;
    }

    /// <summary>
    /// 检查是否有指定类型的Buff
    /// </summary>
    /// <param name="buffType">Buff类型</param>
    /// <returns>是否存在</returns>
    public bool HasBuff(BuffType buffType)
    {
        return m_Buffs.ContainsKey(buffType);
    }


    private void OnDestroy()
    {
        foreach (var buff in m_Buffs)
        {
            buff.Value.Cancel();
        }

        m_Buffs.Clear();
    }
}